﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Net;
using System.IO;
using T2CalcLib.Enums;

namespace EvEPriceData.EvECentralXml
{
    [XmlRoot(ElementName="evec_api")]
    public class EvecApi
    {
        [XmlElement(ElementName="marketstat")]
        public Marketstat Marketstat { get; set; }

        const String EVEC_URL_AND_TYPE = @"http://api.eve-central.com/api/marketstat?typeid=";
        const String EVEC_PARAM_HOURS = @"&hours=";
        const String EVEC_PARAM_ADD_TYPE = @"&typeid=";
        const String EVEC_PARAM_MINQ = @"&minQ=";
        const String EVEC_PARAM_REGION = @"&regionlimit=";
        const String EVEC_PARAM_SYSTEM = @"&usesystem=";

        public static EvecApi Get(List<Int64> typeIDs, 
            Int32 destinationId = 30000142, 
            DestinationTyp destinationTyp = DestinationTyp.System)
        {
            String url = EVEC_URL_AND_TYPE + typeIDs[0];
            url += EVEC_PARAM_HOURS + 72;

            for (int i = 1; i < typeIDs.Count; i++)
            {
                url += EVEC_PARAM_ADD_TYPE + typeIDs[i];
            }

            if (destinationTyp == DestinationTyp.Region)
            {
                url += EVEC_PARAM_REGION + destinationId;
            }

            if (destinationTyp == DestinationTyp.System)
            {
                url += EVEC_PARAM_SYSTEM + destinationId;
            }

            XmlSerializer serializer = new XmlSerializer(typeof(EvecApi));

            HttpWebRequest request =
                (HttpWebRequest)HttpWebRequest.Create(url);

            EvecApi apiData = null;

            try
            {

                using (WebResponse response = request.GetResponse())
                {
                    var stream = response.GetResponseStream();
                    apiData = (EvecApi)serializer.Deserialize(stream);
                }
            }
            catch (Exception)
            {
                // TODO: Fehlerausgabe
            }

            return apiData;

        }


    }
}
